A macro is a textual replacement, which means that it’s not respecting the type system, it’s not respecting scoping rules… There is no reason not
to use a constant instead.
Most of the time, a macro can be replaced by a constexpr
declaration (a constant that is guaranteed to be computed during
compilation). If your compiler is too old to properly handle constexpr
, you may use const
instead.
If you have a series of related integer macros, you might also consider replacing them by an enum
.
Noncompliant code example
#define MAX_MEMORY 640 // Noncompliant
#define LEFT 0 // Noncompliant
#define RIGHT 1 // Noncompliant
#define JUMP 2 // Noncompliant
#define SHOOT 3 // Noncompliant
Compliant solution
constexpr size_t MAX_MEMORY = 640;
enum class Actions {Left, Right, Jump, Shoot};